package com.gjp.processdemo.config.security;

import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.Arrays;
import java.util.Objects;

@Slf4j
@Component
public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {

    @Autowired
    private IdentityService identityService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = identityService.createUserQuery()
                .userLastName(username)
                .singleResult();
        //判断当前用户是否存在
        if (Objects.isNull(user)){
            //测试代码，直接返回Null了
            return null;
        }
        return new org.springframework.security.core.userdetails.User(
                user.getLastName()
                , passwordEncoder.encode(user.getPassword())
                , AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",", Arrays.asList("")))
        );
    }
}
